<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @keyup.enter="onSubmit()"
    >

      <el-form-item label="订单ID" prop="orderId">
        <el-input v-model="dataForm.orderId" placeholder="ID" :disabled="dataForm.id != ''"/>
      </el-form-item>

      <el-form-item label="申请抬头" prop="applyTitle">
        <el-input v-model="dataForm.applyTitle" placeholder="申请抬头"/>
      </el-form-item>

      <el-form-item label="申请原因" prop="applyReason">
        <el-input v-model="dataForm.applyReason" placeholder="申请原因"/>
      </el-form-item>

      <el-form-item label="状态" prop="state">
        <el-radio-group v-model="dataForm.state">
          <el-radio :label="0">申请中 </el-radio>
          <el-radio :label="1" disabled> 已开票 </el-radio>
          <el-radio :label="2" disabled> 申请被驳回 </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { Debounce } from "@/utils/debounce";
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataForm = ref({
  id: "",
  orderId: "",
  applyTitle:"",
  applyReason:"",
  state: 0
});
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10, // 每页显示多少条
});
const dataRule = {
  orderId: [{ required: true, message: "订单ID不能为空", trigger: "blur" }],
  state: [{ required: true, message: "申请状态不能为空", trigger: "blur" }],
  applyTitle: [{ required: true, message: "申请抬头不能为空", trigger: "blur" }],
};

const dataFormRef = ref(null);
const init = (id) => {
  dataForm.value.id = id || 0;
  //dataForm.value = { userId: id } || {};
  visible.value = true;
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
  if (dataForm.value.id) {
    http({
      url: http.adornUrl(`/shop/invoice/info/${dataForm.value.id}`),
      method: "get",
      params: http.adornParams(),
    }).then(({ data }) => {
      dataForm.value = data;
    });
  }
};
defineExpose({ init });

/**
 * 表单提交
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl("/shop/invoice"),
        method: dataForm.value.id ? "put" : "post",
        data: http.adornData({
          ...dataForm.value,
        }),
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
          duration: 1500,
          onClose: () => {
            visible.value = false;
            emit("refreshDataList", page);
          },
        });
      });
    }
  });
});
</script>
